<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/vue@3"></script>
  <title>Document</title>
</head>

<body>
  <div id="app">
    <table border="1" style="border-collapse: collapse;">
      <tr style="background: #eee;">
        <th v-for="(item,index) in colums" :key="index">
          {{ item.title }}
        </th>
      </tr>
      <tr v-for="(row,rowInd) in rows" :key="rowInd">
        <td>
          <input type="text" v-model="row.price" style="width: 80px; margin: 0 10px;">
        </td>
        <td>
          <input type="text"  v-model="row.num" style="width: 80px; margin: 0 10px;">
        </td>
        <td style="width: 80px;">
          <span style="margin: 0 10px;">{{ computedPrice(row) }}</span>
        </td>
      </tr>
    </table>
  </div>
</body>

<script>
  /**
   * 重复计算的函数，使用缓存
   * 例如计算总价，当计算总价方法参数不变，直接返回之前调用的结果，不用再重新调用
  */
  const { ref, computed, createApp } = Vue;
  createApp({
    setup() {
      const rows = ref([
        { price: 23.5, num: 10, },
        { price: 24.5, num: 16, },
        { price: 27.5, num: 18, },
        { price: 27.5, num: 18, },
        { price: 27.5, num: 18, },
        { price: 27.5, num: 18, },
      ])

      const colums = ref([
        { key: 'price', title: '单价'},
        { key: 'num', title: '数量'},
        { key: '', title: '总价'},
      ])

      let count = 0
      const totalPrice = (row) => {
        console.log(111) // 只计算3次
        return row.price * row.num
      }
      // 封装useComputed
      function useComputed(fn) {
        const cache = new Map();

        return function(...args) {
          const cacheResult = cache.get(JSON.stringify(args))
          if(cacheResult) {
            return cacheResult
          } else {
            const result = computed(() => fn(...args))
            cache.set(JSON.stringify(args), result)
            return result
          }
        }
      }

      const computedPrice = useComputed(totalPrice)

      return { rows, colums, computedPrice }
    }

  }).mount('#app')
</script>

</html>
